Android Room
provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite.
Room は、最小限のボイラープレート コードを使用してローカルデータを永続化するオブジェクト マッピング ライブラリです。コンパイル時に各クエリをデータスキーマに照らして検証することで、不完全な SQL クエリがランタイム エラーではなくコンパイル時エラーになるようにします
実装方針
Your Room database class must be abstract and extend RoomDatabase. Usually, you only need one instance of a Room database for the whole app.
例えば、insert(word)をしたいとする
viewModel.insert(word)みたいに activity(fragment)上の viewModelへのinsertメッセージ
repository.insert(word) みたいに viewModel上にあるメソッドのscopeで insert メッセージ
wordDao.insert(word)みたいに repository(Daoを引数にとってプロパティ化して Daoに insertメッセージ
1つ新しい操作をしたいとしたら、
repositoryクラス上で、Daoのinterfaceに SQLを書いて定義
ViewModelクラス上で、
abstract method (DAOを返す)
code: database_sigleton.kt
@Volatile
private var INSTANCE: WordRoomDatabase? = null
fun getDatabase(context: Context, scope: CoroutineScope): WordRoomDatabase {
// if the INSTANCE is not null, then return it,
// if it is, then create the database
return INSTANCE ?: synchronized(this) {
Room.databaseBuilder(context.applicationContext, WordRoomDatabase::class.java, "word_database")
.addCallback(WordDatabaseCallback(scope))
.build().also{
INSTANCE = it
}
}
}
という方針
roomでDatabase インスタンスを作成
インスタンスのメソッドで、abstract で 設定してあるDaoを呼ぶ。
そのDaoをinterface で定義しておいたメソッド(sqlと結びついてる?)で実際のDataBaseに対する操作
原則としては、FireStoreにはoffline persistanceがあるので、Roomは要らない?
ただ、併用するメリットはある?
通常のFireStoreのpersistanceは、LRUキャッシュ?それを超えてlocalに持ちたい?状況がありえる? Realmを使う際は、Android ViewModelにRealmインスタンスのライフサイクルを管理させ、ViewModelが破棄されるタイミングでRealmインスタンスをcloseさせるという使い方ができます codelabがあるので、一度やっておく。